import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class client extends WindowAdapter implements ActionListener{
	Socket client;
	boolean flag;
	BufferedReader cin;
	PrintWriter cout;
	Frame f;
	Button b1;
	TextArea ta;
	TextField tf;

	public client() {
		try{
			client = new Socket("localhost", 1234);
			System.out.println("已建立连接了!");
			this.ChatFrame("Client port:1234");
			flag = true;
			while(flag) {
				InputStream is = client.getInputStream();
				cin = new BufferedReader(new InputStreamReader(is));
				OutputStream os = client.getOutputStream();
				cout = new PrintWriter(os, true);
				String aline;
				while((aline = cin.readLine()) != null) {
					ta.append(aline+"\n");
					if(aline.equals("bye")) {
						flag = false;
						break;
					}
				}
				is.close();
				os.close();
				System.exit(0);
			}
		}catch(Exception e) {
			System.out.println(e);
		}	
	}
	public void ChatFrame(String str) {
		f = new Frame("Client:"+str);
		f.setSize(400, 300);
		ta = new TextArea();
		f.add(ta);
		ta.setEditable(false);
		Panel p = new Panel();
		f.add(p, "South");
		tf = new TextField(20);
		b1 = new Button("Send");
		p.add(tf);
		p.add(b1);
		b1.addActionListener(this);
		tf.addActionListener(this);
		f.setVisible(true);
		f.addWindowListener(this);
	}
	public void actionPerformed(ActionEvent e) {
		ta.append(tf.getText()+"\n");
		cout.println(tf.getText());
		tf.setText("");
	}
	public void windowClosing(WindowEvent e) {
		cout.println("bye");
		System.exit(0);
	}
	public static void main(String arg[]) {
		new client();
	}
}
